﻿using CommonUtil;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net;
using System.Net.Security;
using System.Security.Cryptography.X509Certificates;
using System.Text;
using System.Threading.Tasks;

namespace Infrastructure
{
    /// <summary>
    /// WebApi请求工具
    /// </summary>
    public class WebApiHelper
    {

        #region 构造函数

        /// <summary>
        /// 构造函数
        /// </summary>
        public WebApiHelper()
        {
            AccessToken = "";
        }



        public WebApiHelper(string accessToken)
        {
            AccessToken = accessToken;
        }

        #endregion


        #region 属性


        ///// <summary>
        ///// Key
        ///// </summary>
        //public string Key { get; set; }

        ///// <summary>
        ///// Secret
        ///// </summary>
        //public string Secret { get; set; }

        /// <summary>
        /// 
        /// </summary>
        public string AccessToken { get; set; }

        ///// <summary>
        ///// 签名头
        ///// </summary>
        //public string Authorization
        //{
        //    get
        //    {
        //        var random = Guid.NewGuid().ToString();
        //        var ts = (long)(DateTime.Now.ToUniversalTime() - new DateTime(1970, 1, 1)).TotalMilliseconds;
        //        var signature = EncryptTools.EncryptSHA256(random + ts + Secret);
        //        var authorization = EncryptTools.EncryptionBase64($"{Key}.{random}.{ts}.{signature}");
        //        return authorization;
        //    }
        //}

        #endregion


        #region 数据交互

        /// <summary>
        /// Get
        /// </summary>
        /// <param name="url"></param>
        /// <returns></returns>
        public string Get(string url)
        {
            WebRequest request = WebRequest.Create(url);
            request.Proxy = null;
            request.Credentials = CredentialCache.DefaultCredentials;
            request.Method = "GET";
            request.ContentType = "text/html;charset=UTF-8";
            //if (Key != "")
            //{
            //    request.Headers.Add("Authorization", "Basic " + Authorization);
            //}
            //allows for validation of SSL certificates 
            if (AccessToken != "")
            {
                request.Headers.Add("Access-Token", AccessToken);
            }
            if (url.StartsWith("https"))
            {
                ServicePointManager.ServerCertificateValidationCallback += new RemoteCertificateValidationCallback(ValidateServerCertificate);
            }
            HttpWebResponse response = (HttpWebResponse)request.GetResponse();
            Stream dataStream = response.GetResponseStream();
            StreamReader reader = new StreamReader(dataStream);

            string result = reader.ReadToEnd();
            return result;
            //return JsonConvert.DeserializeObject<dynamic>(responseFromServer);
        }

        /// <summary>
        /// Post
        /// </summary>
        /// <param name="url"></param>
        /// <param name="postdata">Json格式 JsonConvert.SerializeObject(content)</param>
        /// <returns></returns>
        public string Post(string url, string postdata)
        {
            WebRequest request = WebRequest.Create(url);
            request.Proxy = null;
            request.Credentials = CredentialCache.DefaultCredentials;
            request.Method = "Post";
            request.ContentType = "application/json;charset=UTF-8";
            //if (Key != "")
            //{
            //    request.Headers.Add("Authorization", "Basic " + Authorization);
            //}

            if (AccessToken != "")
            {
                request.Headers.Add("Access-Token", AccessToken);
            }


            var postdatabyte = Encoding.UTF8.GetBytes(postdata);
            request.ContentLength = postdatabyte.Length;
            //提交请求
            var stream = request.GetRequestStream();
            stream.Write(postdatabyte, 0, postdatabyte.Length);
            stream.Close();
            //allows for validation of SSL certificates 
            if (url.StartsWith("https"))
            {
                ServicePointManager.ServerCertificateValidationCallback += new System.Net.Security.RemoteCertificateValidationCallback(ValidateServerCertificate);
            }
            HttpWebResponse response = (HttpWebResponse)request.GetResponse();
            Stream dataStream = response.GetResponseStream();
            StreamReader reader = new StreamReader(dataStream);
            return reader.ReadToEnd();
        }

        /// <summary>
        /// Put
        /// </summary>
        /// <param name="url"></param>
        /// <param name="postdata">Json格式 JsonConvert.SerializeObject(content)</param>
        /// <returns></returns>
        public string Put(string url, string postdata)
        {
            WebRequest request = WebRequest.Create(url);
            request.Proxy = null;
            request.Credentials = CredentialCache.DefaultCredentials;
            request.Method = "PUT";
            request.ContentType = "application/json;charset=UTF-8";
            //if (Key != "")
            //{
            //    request.Headers.Add("Authorization", "Basic " + Authorization);
            //}

            if (AccessToken != "")
            {
                request.Headers.Add("Access-Token", AccessToken);
            }

            var postdatabyte = Encoding.UTF8.GetBytes(postdata);
            request.ContentLength = postdatabyte.Length;
            //提交请求
            var stream = request.GetRequestStream();
            stream.Write(postdatabyte, 0, postdatabyte.Length);
            stream.Close();
            //allows for validation of SSL certificates 
            if (url.StartsWith("https"))
            {
                ServicePointManager.ServerCertificateValidationCallback += new System.Net.Security.RemoteCertificateValidationCallback(ValidateServerCertificate);
            }
            HttpWebResponse response = (HttpWebResponse)request.GetResponse();
            Stream dataStream = response.GetResponseStream();
            StreamReader reader = new StreamReader(dataStream);
            return reader.ReadToEnd();
        }

        /// <summary>
        /// Delete
        /// </summary>
        /// <param name="url"></param>
        /// <returns></returns>
        public string Delete(string url)
        {
            WebRequest request = WebRequest.Create(url);
            request.Proxy = null;
            request.Credentials = CredentialCache.DefaultCredentials;
            request.Method = "DELETE";
            request.ContentType = "text/html;charset=UTF-8";
            //if (Key != "")
            //{
            //    request.Headers.Add("Authorization", "Basic " + Authorization);
            //}
            //allows for validation of SSL certificates 
            if (AccessToken != "")
            {
                request.Headers.Add("Access-Token", AccessToken);
            }

            if (url.StartsWith("https"))
            {
                ServicePointManager.ServerCertificateValidationCallback += new System.Net.Security.RemoteCertificateValidationCallback(ValidateServerCertificate);
            }
            HttpWebResponse response = (HttpWebResponse)request.GetResponse();
            Stream dataStream = response.GetResponseStream();
            StreamReader reader = new StreamReader(dataStream);
            return reader.ReadToEnd();
        }

        #endregion


        #region 私有方法

        /// <summary>
        /// 不知道的一个卵，但为了https必须要有【？？？】是啊是啊不然怎么地
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="certificate"></param>
        /// <param name="chain"></param>
        /// <param name="sslPolicyErrors"></param>
        /// <returns></returns>
        private bool ValidateServerCertificate(object sender, X509Certificate certificate, X509Chain chain, SslPolicyErrors sslPolicyErrors)
        {
            return true;
        }

        #endregion

    }
}
